package com.qf.boot1.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.kaptcha.Kaptcha;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.boot1.config.SystemConfig;
import com.qf.boot1.entity.Customer;
import com.qf.boot1.ex.CustomerException;
import com.qf.boot1.service.CustomerService;
import com.qf.boot1.utils.Constant;
import com.qf.boot1.vo.CustomerVo;
import com.qf.boot1.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;


/**
 * @author 刘欣
 * @createTime 2023/1/9 19:13
 * @description
 */
@RestController
@RequestMapping("/customer")
@Slf4j
public class CustomerController {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private Kaptcha kaptcha;

    @Value("${upFilePath}")
    private String upFilePath;

    @RequestMapping("/login")
    @ResponseBody
    public ResultVo login(@RequestBody @Valid CustomerVo customerVo, HttpServletResponse response, HttpServletRequest request, HttpSession session) {
        log.debug("接受到的参数,customerVo={}", customerVo);
        String circuitChanger = customerVo.getCircuitChanger();
        System.out.println(circuitChanger);
        String sessionCaptchar = (String) session.getAttribute(Constant.KAPTCHA_SESSION_KEY);
        String captcharVo = customerVo.getCaptchar();
        String customerVoUsername = customerVo.getName();
        String customerVoPassword = customerVo.getPassword();
        //对验证码校验
        if (!sessionCaptchar.equals(captcharVo)) {
            //验证码错误
            ResultVo resultVo = ResultVo.error("验证码错误");
            return resultVo;
        }
//        kaptcha.validate(customerVo.getCaptchar());
        //根据用户名和密码查询customer
        Customer customer = customerService.selectByUsernameAndPassword(customerVoUsername, customerVoPassword);
        if (customer != null) {
            //对免登入进行校验
            if ("on".equals(circuitChanger)) {
                Cookie customerCookie = new Cookie(Constant.CUSTOMER_COOKIE_KEY, customerVoUsername + "-" + DigestUtil.md5Hex(customerVoUsername));
                customerCookie.setPath(request.getContextPath() + "/");
                customerCookie.setMaxAge(60*60*24*14);
                response.addCookie(customerCookie);
            } else {
                Cookie cookieRemove = new Cookie(Constant.CUSTOMER_COOKIE_KEY, null);
                cookieRemove.setPath(request.getContextPath() + "/");
                cookieRemove.setMaxAge(0);
                response.addCookie(cookieRemove);
            }
            //登成功
            ResultVo resultVo = ResultVo.ok();
            resultVo.put("data", customer);
            session.setAttribute(Constant.CUSTOMER_SESSION_KEY, customer);
            return resultVo;
        } else {
            //登入用户名或密码错误
            ResultVo resultVo = ResultVo.error("用户名或密码错误");
            return resultVo;
        }
    }


    @RequestMapping("/register")
    public ResultVo insertCustomer(CustomerVo customerVo, MultipartFile file, HttpSession session) throws IOException {
        log.debug("接受参数,custromer={},file={}", customerVo.toString(), file);
        String captchar = (String) session.getAttribute(Constant.KAPTCHA_SESSION_KEY);
        String customerVoCaptchar = customerVo.getCaptchar();
        if (!captchar.equals(customerVoCaptchar)) {
            return ResultVo.error("验证码错误！");
        }
        int i = customerService.register(customerVo, file);
        if (i > 0) {
            return ResultVo.ok();
        } else {
            return ResultVo.error();
        }
    }

    @RequestMapping("/chekcusername")
    public ResultVo checkUsername(String username) throws CustomerException {
        if (username == null) {
            return ResultVo.error("请填写用户名");
        }
        Customer customer = new Customer();
        customer.setName(username);
        customerService.selectCustomer(customer);
        return ResultVo.ok();
    }

    //分页查询
    @RequestMapping("/getall")
    public ResultVo getPageQuery(Integer page, Integer limit, CustomerVo customerVo) throws CustomerException {
        log.debug("接受到的参数page={},limit={},customer={}", page, limit, customerVo);
        PageHelper.startPage(page, limit);
        List<Customer> customers = customerService.selectAll();
        PageInfo<Customer> customerPageInfo = new PageInfo<>(customers);
        long total = customerPageInfo.getTotal();
        if (customers == null) {
            return ResultVo.error("请添加用户");
        }
        ResultVo resultVo = ResultVo.ok(0, "ok");
        resultVo.put("count", total);
        resultVo.put("data", customers);
        System.out.println(customers.toString());
        return resultVo;
    }

    //添加
    @RequestMapping("/add")
    public ResultVo add(CustomerVo customerVo) throws CustomerException {
        log.debug("接受到的参数为，customerVo={}", customerVo);
        customerService.addCustomer(customerVo);
        return ResultVo.ok();
    }

    //删除
    @RequestMapping("/del")
    public ResultVo del(Long[] ids) throws CustomerException {
        log.debug("接受到的参数为，ids={}", ids);
        customerService.deleteByPrimaryKey(ids);
        return ResultVo.ok();
    }

    //编辑
    @RequestMapping("/update")
    public ResultVo update(CustomerVo customerVo) throws CustomerException {
        log.debug("接受到的参数为，customerVo={}", customerVo);
        customerService.updateByPrimaryKey(customerVo);
        return ResultVo.ok();
    }
    //批量导出

    @RequestMapping("/export")
    public ResultVo exprot() {
        List<Customer> customers = customerService.selectAll();
        String filename = customerService.exprot(customers);
        log.debug("批量导出：{}", filename);
        ResultVo vo = ResultVo.ok();
        vo.put("data", filename);
        return vo;
    }
    //批量上传

    //当前登入用户
    @RequestMapping("/currentCustomer")
    public ResultVo currentCustomer(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Customer customer = (Customer) session.getAttribute(Constant.CUSTOMER_SESSION_KEY);
        ResultVo vo = ResultVo.ok();
        vo.put("data", customer);
        return vo;
    }

    @RequestMapping("/currentCustomerPhoto")
    public void currentCustomerPhoto(String filename, HttpServletResponse response) throws IOException {
        String fianlFilename = upFilePath + filename;

        IOUtils.copy(new FileInputStream(fianlFilename), response.getOutputStream());
    }
}
